# app/utils/response_utils.py
from flask import jsonify,request
import json
from datetime import datetime


class ResponseCode:
    # 成功
    SUCCESS = 0

    # 通用错误
    PARAM_ERROR = 1000  # 参数错误
    VALIDATION_FAILED = 1001  # 数据验证失败
    RESOURCE_NOT_FOUND = 1002  # 资源未找到
    PERMISSION_DENIED = 1003  # 无操作权限
    OPERATION_NOT_ALLOWED = 1004  # 操作不被允许
    RATE_LIMIT_EXCEEDED = 1005  # 请求频率过高

    # 身份认证相关
    UNAUTHORIZED = 2000  # 未授权
    INVALID_TOKEN = 2001  # 无效令牌
    TOKEN_EXPIRED = 2002  # 令牌过期
    LOGIN_REQUIRED = 2003  # 需要登录
    INVALID_CREDENTIALS = 2004  # 无效凭据
    ACCOUNT_NOT_FOUND = 2005  # 账号不存在

    # 用户相关
    USERNAME_EXISTS = 3000  # 用户名已存在
    EMAIL_EXISTS = 3001  # 邮箱已注册
    PASSWORD_TOO_WEAK = 3002  # 密码强度不足
    USER_BLOCKED = 3003  # 用户被冻结

    # 服务器错误
    DATABASE_ERROR = 5000  # 数据库错误
    NETWORK_ERROR = 5001  # 网络错误
    THIRD_PARTY_ERROR = 5002  # 第三方服务错误
    UNKNOWN_ERROR = 5999  # 未知错误


def api_response(code=ResponseCode.SUCCESS, data=None, message='', http_code=200, meta=None):
    """创建统一API响应"""
    response = {
        "code": code,
        "message": message or _get_default_message(code),
        "data": data or {},
        "timestamp": datetime.now().isoformat()
    }

    # 添加分页等元信息
    if meta:
        response["meta"] = meta

    # 在开发环境中添加调试信息
    if http_code >= 400:
        # 在生产环境中删除堆栈跟踪
        # 在实际应用中，考虑从环境变量判断
        from flask import current_app
        if current_app.config.get('DEBUG', True):
            import traceback
            response["debug"] = {
                "exception": traceback.format_exc(),
                "request": {
                    "method": request.method,
                    "path": request.path,
                    "headers": dict(request.headers)
                }
            }

    return jsonify(response), http_code


def success_response(data=None, message='操作成功', meta=None):
    """创建成功响应"""
    return api_response(
        code=ResponseCode.SUCCESS,
        data=data,
        message=message,
        meta=meta
    )


def error_response(code=ResponseCode.UNKNOWN_ERROR, message='操作失败', http_code=400):
    """创建错误响应"""
    return api_response(
        code=code,
        message=message,
        http_code=http_code
    )


def _get_default_message(code):
    """获取默认错误消息"""
    messages = {
        ResponseCode.SUCCESS: "操作成功",
        ResponseCode.PARAM_ERROR: "参数错误",
        ResponseCode.VALIDATION_FAILED: "数据验证失败",
        ResponseCode.RESOURCE_NOT_FOUND: "资源不存在",
        ResponseCode.PERMISSION_DENIED: "没有权限执行此操作",
        ResponseCode.OPERATION_NOT_ALLOWED: "当前操作不被允许",
        ResponseCode.RATE_LIMIT_EXCEEDED: "请求过于频繁，请稍后再试",
        ResponseCode.UNAUTHORIZED: "未经授权访问",
        ResponseCode.INVALID_TOKEN: "无效的访问令牌",
        ResponseCode.TOKEN_EXPIRED: "访问令牌已过期",
        ResponseCode.LOGIN_REQUIRED: "需要登录后才能访问",
        ResponseCode.INVALID_CREDENTIALS: "用户名或密码不正确",
        ResponseCode.ACCOUNT_NOT_FOUND: "账号不存在",
        ResponseCode.USERNAME_EXISTS: "用户名已存在",
        ResponseCode.EMAIL_EXISTS: "该邮箱已注册",
        ResponseCode.PASSWORD_TOO_WEAK: "密码强度不足",
        ResponseCode.USER_BLOCKED: "账号已被冻结",
        ResponseCode.DATABASE_ERROR: "数据库操作出错",
        ResponseCode.NETWORK_ERROR: "网络连接异常",
        ResponseCode.THIRD_PARTY_ERROR: "第三方服务错误",
        ResponseCode.UNKNOWN_ERROR: "未知错误，请稍后再试"
    }
    return messages.get(code, "未知错误")